﻿using System;
using System.Collections;
using System.Reflection;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Xml.Linq;

using LINQToolKit.Text;
using LINQToolKit.Processors;
using LINQToolKit.Mapping;

namespace LINQToolKit.Douban.Processors
{
    public sealed class DoubanEntityProcessor : EntityProcessor
    {
        public override string ToInsertXml(MetaEntity model, object entity)
        {
            entity.AssertNull("entity");

            var fileName = string.Format(
                "Posts/{0}.post.config", entity.GetType().Name.ToLower());
            var path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, fileName);

            return XmlTemplate.Load(path, Encoding.UTF8, false).Translate(entity);
        }

        public override string ToUpdateXml(MetaEntity model, object entity)
        {
            entity.AssertNull("entity");
            var fileName = string.Format(
                "Posts/{0}.put.config", entity.GetType().Name.ToLower());
            var path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, fileName);

            return XmlTemplate.Load(path, Encoding.UTF8, false).Translate(entity);
        }

        protected override IList<XElement> GetSubEntries(XElement feed)
        {
            XNamespace ns = "http://www.w3.org/2005/Atom";

            if (feed.Name == ns + "feed")
            {
                return feed.Elements(ns + "entry").ToList();   
            }

            return new List<XElement>(new XElement[]{feed});
        }
    }
}
